<template>
<!--积分商城  -->
<view class="wrap">
  <!--头部的积分  -->
  <view class="jiFen" :style="'background:' + defaultColor">
    <view class="box" @tap="click">
      <view class="userInfo">
        <image :src="loginUser.userIcon + '?x-oss-process=style/preview_120'" style="width:100rpx;height:100rpx;border-radius:100rpx"></image>
        <text style="margin-left:10rpx;color:#fff;font-size:28rpx">{{loginUser.nickName}}</text>
      </view>
      <view class="jiFenInfo">
        <!-- <view class='jiFenBox'><text style='font-size:28rpx'>当前积分:</text></view> -->
        <view class="jiFenBox"><text style="font-size:28rpx">查看积分</text></view>
        <view class="jiFenImg"><image src="https://image1.sansancloud.com/xianhua/2019_12/19/10/48/59_626.jpg?x-oss-process=style/preview_120"></image></view> 
      </view>
    </view>
  </view>

  <view class="main_box">
    <!-- 左边导航 -->
    <scroll-view scroll-y class="left_box">
        <view v-for="(type, index) in jifenTypeList" :key="index" :data-type="type" @tap="bindTypeItem" :class="(type.active?'activeTypeItem':'TypeItem')">
          <block v-if="!!type.iconImage">
            <image class="TypeItem_iamge" mode="aspectFit" :src="type.iconImage"></image>
          </block>
          <block v-else></block>
          <text>{{type.name}}</text>
          </view>
        
        <!-- <view class='ToOrderView_container'>
          <block wx:if='{{pushItem.length > 0}}'>
            <view class='ToOrderView ToOrderView1' data-link='order_list_0.html?easyStatusName=全部订单&easyStatus=0' bindtap='toOrderPage'>
              <image mode='aspectFill' src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/40_186.jpg?x-oss-process=style/preview_120'></image>
              <text>订单</text>
            </view>
          </block>
          <block wx:else>
          <view class='ToOrderView ToOrderView2' data-link='order_list_0.html?easyStatusName=全部订单&easyStatus=0' bindtap='toOrderPage'>
            <image mode='aspectFill' src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/40_186.jpg?x-oss-process=style/preview_120'></image>
            <text>订单</text>
          </view>
          </block>
        </view> -->
          
        <view class="bottomHeight"></view>
    </scroll-view>
    <!-- 右边的商品列表 -->
    <scroll-view scroll-y @scrolltolower="onReachBottom2" class="right_box">
      <image mode="widthFix" :src="currentItem.adverImg" style="width:100%;" v-if="currentItem.adverImg&&currentItem.adverImg!=', '"></image>
      <view v-if="!jiFenGoods" class="nonePro">
        <image mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_12/17/11/9/46_337.jpg?x-oss-process=style/preview_120"></image>
        <text>没有相关商品</text>
      </view>
      <view class="productItem" :data-info="result" @tap="tolinkUrl" v-for="(result, index) in jiFenGoods" :key="index">
          <view class="productItemImage">
            <image mode="aspectFill" class="productImg" :src="result.icon + '?x-oss-process=style/preview'"></image>
          </view>
          <view class="productInfo">
            <view class="productInfo_name">{{result.name}}</view>
            <view class="productInfo_decribe">
              <text class="productInfo_promotionName" :style="'background:' + setting.platformSetting.defaultColor">库存:{{result.count}}</text>
            </view>
            <view class="productInfo_Price">

              <view class="price_group">
                <text class="price">{{result.needJifen}}积分</text>
              </view>
              <view class="productInfo_Nums">
                <view class="choose_measureItem" :style="'background-color: ' + defaultColor + ';padding:8rpx 10rpx;border-radius:10rpx;font-size:20rpx;color:#fff'" @click.stop="buyGoods" :data-id="index">兑换</view>
              </view>

            </view>
          </view>
      </view>
      <view class="bottomHeight"></view>
    </scroll-view>
    <!-- <view class='right_box'>
    
      <block  wx:if="{{jiFenGoods.length!=0}}">
    
        <view class='detail_list_mode1' style='background:  #eeeeee;'>
          <view class="mode1_items" data-info="{{jiFenGoods}}" bindtap='tolinkUrl' wx:for="{{jiFenGoods}}" wx:for-item="jiFenGoods" wx:key="{{index}}" 
            style='border-right: 10px solid #eeeeee;'> 
            
            <image  mode='aspectFill'  src="{{jiFenGoods.icon}}"></image>
            <view class='center' style='width:{{(1/jsonData.column)*sysWidth-40}}px;'>{{jiFenGoods.name}}</view>
          <view class='NewBox'>
            <text class='ml20'>{{jiFenGoods.needJifen}}积分</text>
            <text class='mr20'>库存:{{jiFenGoods.count}}</text>
          </view>
          
        <view class='exchange' style='background-color: {{defaultColor}};' catchtap='buyGoods' data-id='{{index}}'><text style='color:#fff;'>兑换</text></view>
          
    
          </view>
        </view>
      </block>

      <block wx:if="{{jiFenGoods.length==0}}">
        <view class="noproduct">
          <image mode="widthFix" src='/images/icons/no-product.png'></image>
          <text>没有相关商品</text>
        </view>
      </block>
    </view> -->
  </view>


</view>
</template>

<script>
var timer11; // 计时器

export default {
  data() {
    return {
      jiFen: "",
      jiFenGoods: [],
      defaultColor: "",
      //主色调
      secondColor: "",
      //副色调
      jifenTypeList: [],
      page: 1,
      pageSize: 6,
      //
      totalSize: 0,
      //总量
      curpage: 1 //当前页
      ,

      /* 全部参数 */
      params: {
        type: 0
      },
      curPage: "",
      setting: "",
      loginUser: "",
      positionTab: ""
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    // 主色调
    let that = this;
    that.getJifenTypeData();
    that.getSessionUserInfo()
    console.log(JSON.stringify(getApp().globalData.setting.platformSetting.defaultColor));
    console.log(JSON.stringify(getApp().globalData.setting.platformSetting.secondColor));
    that.setData({
      defaultColor: getApp().globalData.setting.platformSetting.defaultColor,
      secondColor: getApp().globalData.setting.platformSetting.secondColor,
      setting: getApp().globalData.setting
    });
    console.log(that.setting);
    console.log(that.loginUser); //  已经登录

    if (getApp().globalData.loginUser && getApp().globalData.loginUser != "") {
      // console.log("已经登录了" + JSON.stringify(app.loginUser))
      that.setData({
        jiFen: getApp().globalData.loginUser.jifen
      });
    } else {
      that.setData({
        jiFen: "您还未登录"
      });
    }

    if (options && options.parentTypeId) {
      that.setData({
        positionTab: options.parentTypeId
      });
      that.getProductType(options.parentTypeId, that.bindTypeItem);
    } else {
      that.getData();
    }
  },
  onReady: function () {},
  onShow: function () {},
  onPullDownRefresh: function () {
    this.jiFenGoods = [];
    this.curPage = 1;
    this.onLoad();
    wx.stopPullDownRefresh();
  },
  methods: {
    getSessionUserInfo: function () {
      var that = this;
      var postParamUserBank = getApp().globalData.AddClientUrl("/get_session_userinfo.html");
      wx.request({
        url: postParamUserBank.url,
        data: postParamUserBank.params,
        header: getApp().globalData.headerPost,
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode == '0') {
            let UserInfo = res.data.relateObj.platformUser;
            let orderData = that.orderData;
            let loginUser = res.data.relateObj;
            that.setData({
              loginUser: loginUser,
              setting: getApp().globalData.setting,
            }); // 11111

            getApp().globalData.loginUser = res.data.relateObj;
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
          }
        },
        fail: function (res) {
          console.log(res.data);
        },
        complete: function (res) {
          wx.stopPullDownRefresh();
        }
      });
    },
    /* 点击分类大项 */
    bindTypeItem: function (event) {
      console.log(event.currentTarget.dataset.type);
      let focus = event.currentTarget.dataset.type;
      let that = this;

      for (let i = 0; i < that.jifenTypeList.length; i++) {
        if (that.jifenTypeList[i].id == event.currentTarget.dataset.type.id) {
          that.jifenTypeList[i].active = true;
        } else {
          that.jifenTypeList[i].active = false;
        }
      }

      that.setData({
        jifenTypeList: that.jifenTypeList
      });
      that.page = 1;

      if (event.currentTarget.dataset.type.id == "all") {
        that.params.type = 0;
        that.getData(this.params);
      } else {
        that.params.type = focus.id;
        that.getData(this.params); //}
      }
    },
    getJifenTypeData: function (categoryId) {
      console.log('-------getJifenTypeData--------');
      let getParam = {};
      var customIndex = getApp().globalData.AddClientUrl("/super_mini_find_jifen_types.html", getParam);
      var that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          let jifenTypeList = res.data.relateObj.result;
          jifenTypeList.unshift({
            id: categoryId || 0,
            name: "全部"
          });

          for (let i = 0; i < jifenTypeList.length; i++) {
            jifenTypeList[i].colorAtive = '#888';
          }

          jifenTypeList[0].colorAtive = that.setting.platformSetting.defaultColor;
          jifenTypeList[0].active = true;
          that.setData({
            jifenTypeList: jifenTypeList
          });
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    tolinkUrl: function (e) {
      console.log(e.currentTarget.dataset.info);
      let info = e.currentTarget.dataset.info;
      let jifenId = info.id;
      let productId = info.productId;
      let couponId = info.couponId;
      let jifenNum = info.needJifen;
      let jifenCount = info.count;

      if (productId) {
        var a = "jifen_product_detail.html?type=jifen&productId=" + productId + '&jifenNum=' + jifenNum + '&jifenId=' + jifenId + '&jifenCount=' + jifenCount;
      }

      if (couponId) {
        var a = "coupon_detail.html?type=jifen&couponId=" + couponId;
      }

      getApp().globalData.linkEvent(a);
    },
    // 测试跳去积分
    click: function () {
      wx.navigateTo({
        url: '/pages/user_jifen_events/index'
      });
    },
    // 兑换商品
    buyGoods: function (e) {
      var that = this;
      console.log(e.currentTarget.dataset.id);
      wx.showModal({
        title: '提示',
        content: '确定兑换商品',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.exchange(e.currentTarget.dataset.id);
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    //兑换
    exchange: function (index) {
      console.log("======a=======", index);
      var that = this;
      console.log("======a=======", that.jiFenGoods[index]); // 判断是否已经兑换过

      if (that.jiFenGoods[index].count <= 0) {
        wx.showToast({
          title: "超出兑换上限",
          image: '/wxcomponents/images/icons/tip.png',
          duration: 2000
        });
      } else {
        var id = that.jiFenGoods[index].id;
        let exchange = {
          jifenItemId: id,
          fromSource: "wx"
        };
        let menDianYangShi = getApp().globalData.AddClientUrl("/jifen_exchange_phone_json.html", exchange, 'get');
        wx.request({
          url: menDianYangShi.url,
          data: menDianYangShi.params,
          header: getApp().globalData.headerPost,
          method: 'get',
          success: function (res) {
            console.log("======a=======", res);

            if (res.data.errcode == "-1") {
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              });
              console.log(res.data.errMsg);
            } else {
              wx.showToast({
                title: "兑换成功",
                image: '/wxcomponents/images/icons/targ.png',
                duration: 2000
              }); // 兑换成功后次数减少

              var time = that.jiFenGoods;
              console.log("time", time[index].count--);
              time[index].count = time[index].count--;
              that.setData({
                jiFenGoods: time
              });
            }
          }
        });
      }
    },
    getData: function (param) {
      let exchange = {};
      exchange.page = this.page;

      if (param) {
        exchange = Object.assign({}, exchange, param);
      }

      var customIndex = getApp().globalData.AddClientUrl("/super_mini_shop_find_jifen_items.html", exchange, 'get');
      var that = this; //拿custom_page

      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        method: 'get',
        success: function (res) {
          if (res.data.errcode < 0) {
            that.setData({
              jiFenGoods: []
            });
          } else {
            console.log(res.data.relateObj.result); // 获取到的数据要添加进原先的数据

            let newGoods = that.jiFenGoods;

            if (that.page == 1) {
              newGoods = res.data.relateObj.result;
            } else {
              newGoods = newGoods.concat(res.data.relateObj.result);
            }

            console.log(newGoods);
            that.setData({
              pageSize: res.data.relateObj.pageSize,
              curPage: res.data.relateObj.curPage,
              totalSize: res.data.relateObj.totalSize,
              jiFenGoods: newGoods
            });
          }
        },
        fail: function (res) {}
      });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom2: function () {
      var that = this; // 1 6 20 1

      console.log(that.page);
      console.log(that.totalSize);
      console.log(that.pageSize);
      console.log(that.curPage); // 当总量大于当前页*数量的时候

      if (that.totalSize > that.curPage * that.pageSize) {
        console.log("1111111");
        let page = that.page;
        page++;
        that.setData({
          page: page
        });
        that.getData();
      }
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>